package net.orange.console.model.analyzer;

import java.util.Collection;

import net.orange.console.model.dataset.ConsoleDataType;
import net.orange.console.model.dataset.ConsoleMetaData;

/**
 * The analyse data key pair, it usually use in the data key sorting.
 */
public class AnalyseDataKeyPair {
	/**
	 * The data key.
	 */
	String key;
	/**
	 * The analyse dimension.
	 */
	Collection<AnalyseDimension> analyseDimensions;

	/**
	 * Constructor with key and AnalyseDimension.
	 */
	public AnalyseDataKeyPair(String key,
			Collection<AnalyseDimension> analyseDimension) {
		this.key = key;
		this.analyseDimensions = analyseDimension;
	}

	/**
	 * @return the key
	 */
	public String getKey() {
		return key;
	}

	/**
	 * @param key
	 *            the key to set
	 */
	public void setKey(String key) {
		this.key = key;
	}

	/**
	 * @return the analyseDimension
	 */
	public Collection<AnalyseDimension> getAnalyseDimensions() {
		return analyseDimensions;
	}

	/**
	 * @param analyseDimension
	 *            the analyseDimension to set
	 */
	public void setAnalyseDimensions(
			Collection<AnalyseDimension> analyseDimensions) {
		this.analyseDimensions = analyseDimensions;
	}

	/**
	 * Compare another AnalyseDataKeyPair
	 * 
	 * @param p2
	 *            The another AnalyseDataKeyPair
	 * @return 1 if this bigger than p2, 0 if they are equal, -1 for small than
	 *         p2
	 */
	public int compareTo(AnalyseDataKeyPair p2) {

		String dim1[] = key.split(AnalyseDimension.DIM_DIM_SEPARATOR);
		String dim2[] = p2.getKey().split(AnalyseDimension.DIM_DIM_SEPARATOR);

		if (dim1 == null || dim1.length <= 0)
			return -1;

		if (dim2 == null || dim2.length <= 0)
			return 1;

		String[] keys1 = dim1[0].split(AnalyseDimension.KEY_KEY_SEPARATOR);
		String[] keys2 = dim2[0].split(AnalyseDimension.KEY_KEY_SEPARATOR);

		Object[] dimensions = analyseDimensions.toArray();

		for (int i = 0; i < keys1.length; ++i) {
			if (!keys1[i].equals(keys2[i])) {
				ConsoleMetaData metaData = ((AnalyseDimension) dimensions[i])
						.getMetaData();

				if (metaData.getDataType() == ConsoleDataType.Integer
						|| metaData.getDataType() == ConsoleDataType.Numberic) {

					return (int) (Double.valueOf(keys1[i]) - Double
							.valueOf(keys2[i]));

				} else
					return keys1[i].compareTo(keys2[i]);
			}
		}

		return 0;
	}
}
